const state = {
  // count: 10,
  cartList: JSON.parse(localStorage.getItem('goods') || '[]'),
};

const mutations = {
  // 商品详情页 将商品添加至购物车
  addGoods(state, goodsInfo) {
    let flag = false;

    state.cartList.some((item) => {
      if (item.id == goodsInfo.id) {
        item.count += goodsInfo.count;
        flag = true;
      }
    });

    if (!flag) {
      state.cartList.push(goodsInfo);
    }
    localStorage.setItem('goods', JSON.stringify(state.cartList));
  },

  // 增加商品
  addAssign(state, id) {
    state.cartList.some((item) => {
      if (item.id == id) {
        item.count++;
      }
    });
    localStorage.setItem('goods', JSON.stringify(state.cartList));
  },
  //减少商品
  reduceAssign(state, id) {
    state.cartList.some((item) => {
      if (item.id == id) {
        item.count--;
      }
    });
    localStorage.setItem('goods', JSON.stringify(state.cartList));
  },
  //删除商品
  deleteGoods(state) {
    // 过滤出selected为false的每一项,
    //然后再把filter返回出新数组重新赋给原数组,以达到删除的效果
    state.cartList = state.cartList.filter((item) => item.selected == false);
    localStorage.setItem('goods', JSON.stringify(state.cartList));
  },

  // 点击全选和反选,改变cartlist中每一项的selected状态
  toggle_checked_all(state, selected) {
    state.cartList.forEach((item) => {
      item.selected = selected;
    });
    localStorage.setItem('goods', JSON.stringify(state.cartList));
  },
};

const actions = {};

const getters = {
  // 计算购物车中所有类型商品的总数量
  getAllCount(state) {
    let num = 0;
    state.cartList.forEach((item) => {
      num += item.count;
    });
    return num;
  },
  //购物车底部的价格合计
  getAllPrice(state) {
    let price = 0;
    state.cartList.forEach((item) => {
      //该订单项的复选框打钩了才参与计算总价
      if (item.selected) {
        price += item.count * item.price;
      }
    });
    return price;
  },
  getCheckBox(state) {
    //全选反选框的状态,取决于购物车中每一项的复选框状态,当所有的都打钩时才打钩
    return state.cartList.every((item) => item.selected);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
